const router = require('koa-router')();

const { sendVerificationCode, verifyCode } = require('../controller/email');
const { findDuplicateUser } = require('../controller/user');
const { SuccessResponse, ErrorResponse } = require('../model/Response');

router.prefix('/api/email');

// send verification code
router.post('/send', async function (ctx) {
  const { email } = ctx.request.body;
  const existResult = await findDuplicateUser({ email });
  if(existResult.exist){
    ctx.body =  new ErrorResponse('邮箱已被使用');
    return
  }
  const result = await sendVerificationCode(email);
  if(!result){
    ctx.body =  new ErrorResponse();
  }
  if(result.cooling){
    ctx.body = new ErrorResponse('发送频率过高');
    return
  }
  ctx.body = new SuccessResponse({ expireTime: result.expireTime });
});

// verify
router.post('/verify', async function (ctx) {
  const { email, code } = ctx.request.body;
  const result = await verifyCode(email, '' + code );
  ctx.body = result ? new SuccessResponse() : new ErrorResponse('校验未通过');
});

module.exports = router;
